from MyHttp import *
from huobi import HbData
from okex import OkData
from binance import BianData
from bfx import BfxData
from gate import GateData
from zb import ZbData
from bittrex import BitData
#from binance import BianPrice
from poloniex import PolData
from hitbtc import HitbtcData
import json
import time, threading
import requests

#huobi
ACCESS_KEY = "118557d8-f3bb5588-dab571dd-f77c9"
SECRET_KEY = "aa5cc798-6c67f62d-53ce2bf9-4f88b"
#ok
ACCESS_KEY = "ea252b6d-1976-4ae6-9ead-3c9a95e669f9"
SECRET_KEY = "D54AD06C7AC88D376716CF670F2B8796"
#bian
ACCESS_KEY = "uEaaU6eIvQVKF4VEhoWxrzMb5ExpCaFXZdJKILNH4UVhKmW3NBVolAsxYeeoq5D6"
SECRET_KEY = "UAFJWW5mx991mfXpM2gXJvlBdMKJbdtgj9kCT28TPQwSpYY9X50QCldYE4Gnwsrg"
#bfx
ACCESS_KEY = "pXqrQg9gam4TxnM8zV0M1nwTdE9E3dqxDOTQ5JSWyo3"
SECRET_KEY = "D8dr8iJAFRaIYcAIhaH8DmZF84cVxYegR2O4CfC6mEX"
#gate
ACCESS_KEY = "2C62B782-9F71-4259-81B3-EA49BFAD98B3"
SECRET_KEY = "46fe0a1ed1f5292f44e93074ba397c43f4955eb780b5ecefdf4d2b96278c933a"
#zb
ACCESS_KEY = "9de399f5-22df-4e1e-9775-548cb9122219"
SECRET_KEY = "ec0b3f76-0031-4d6e-99af-26d51a31c012"

#BianPrice.StartSocket()
cp = {}
#print(BianPrice.cp)

pingtai = {'huobi':HbData,'okex':OkData,'binance':BianData,'bfx':BfxData,'gate':GateData,'zb':ZbData,'bittrex':BitData,'poloniex':PolData,'hitbtc':HitbtcData}

users = GetUserInfo()
markets = GetMarket()

for user in users:
    thelist = []
    for market in markets:
        if user['user'] == market['user']:
            thelist.append(market)
    user['market'] = thelist

def GetPrice(coinjson):
    price = 0.0
    for i in coinjson.keys():
        if i in cp.keys():
            price = price + coinjson[i] * cp[i]
            price = int(price * 100)/100
    return price


def loop(user, noce):
    try:
        coinjson = json.loads('{}')
        for market in user['market']:
            print(market['name'])
            pingtai[market['name']].GetCoinNum(coinjson, market['ak'], market['sk'])
        # print(coinjson)
        if 'bch' in coinjson:
            if 'bcc' in coinjson:
                coinjson['bcc'] = coinjson['bcc'] + coinjson['bch']
            else:
                coinjson['bcc'] = coinjson['bch']
            del coinjson['bch']
        price = GetPrice(coinjson)
        # print(price)

        # print(user['up_time'])
        if int(user['up_time']) == noce:
            print('updata数据库')
            if not ('coins' in user):
                oldcoins = json.loads('{}')
                coins = Gettotalcoins(user['user'], noce - 1)
                wwww = coins['coins']
                wwww = wwww.replace('\'', '\"')
                oldcoins = json.loads(wwww)
                user['coins'] = oldcoins

            coincha = {}
            print('up_time')
            for i in coinjson.keys():
                if i in user['coins'].keys():
                    chajia = coinjson[i] - float(user['coins'][i])
                    if chajia > 0 or chajia < 0:
                        coincha[i] = chajia
                else:
                    coincha[i] = coinjson[i]
            #print('差价:' + str(coincha))
            pricecha = GetPrice(coincha)
            Update(user['user'], noce, coinjson, price, coincha, pricecha)
            print('updata数据库，做差价updata数据库:')
        elif int(user['up_time']) == noce - 1:
            print('insert数据库')

            coincha = {}
            for i in coinjson.keys():
                if i in user['coins'].keys():
                    chajia = coinjson[i] - float(user['coins'][i])
                    if chajia > 0 or chajia < 0:
                        coincha[i] = chajia
                else:
                    coincha[i] = coinjson[i]
            pricecha = GetPrice(coincha)
            Insert(user['user'], noce, coinjson, price, coincha, pricecha, float(user['shouyi']) + pricecha)
            user['up_time'] = noce
            coins = Gettotalcoins(user['user'], noce - 1)
            wwww = coins['coins']
            wwww = wwww.replace('\'', '\"')
            oldcoins = json.loads(wwww)
            user['coins'] = oldcoins
            if user['user1'] != "0":
                fencheng1 = pricecha*0.07
                Fencheng(user['user1'],noce,fencheng1)
                if user['user2'] != "0":
                    fencheng2 = pricecha * 0.03
                    Fencheng(user['user2'], noce, fencheng2)
            print('insert数据库2')
        elif int(user['up_time']) == 0:
            print('初始化')
            Initial(user['user'], noce, coinjson, price)
            user['coins'] = coinjson
            user['up_time'] = noce
            print('insert前一天的数据库,insert数据库')
            print(user['coins'])
    except Exception as e:
        print('Error:', e)

jishu = 0
while 1:
    pric = GetCoinprice()
    cp = json.loads(pric['prices'])
    jishu = jishu + 1
    print('运行时间'+ time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    noce = int((time.time() / 60 / 60 + 8) / 24)
    for user in users:
        print(user['user'])
        t = threading.Thread(target=loop, args=(user,noce))
        t.start()
        time.sleep(2)

    time.sleep(60)
#print(userinfo.json())

#HbDate.GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
#OkData.GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
#BianData.GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
#BfxData.GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
#GateData.GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
try:
    #pingtai['zb'].GetCoinNum(coinjson, ACCESS_KEY, SECRET_KEY)
    print("退出了")
except Exception as e:
    print('Error:', e)
#GetCoinNum(coinjson)
